package com.ice.netty.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.ice.framework.common.annotation.AutoResult;
import com.ice.netty.modbus.server.NettyTestServer;
import com.ice.netty.web.dto.ScanCodeOpenReq;
import com.ice.remoting.data.RemotingCommand;
import com.ice.remoting.exception.RemotingConnectException;
import com.ice.remoting.exception.RemotingSendRequestException;
import com.ice.remoting.exception.RemotingTimeoutException;
import com.ice.remoting.utils.NetUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@AutoResult
@RestController
public class DeviceInfoController {

    @Autowired
    private NettyTestServer nettyTestServer;

    @PostMapping("/scanCodeOpen")
    public void scanCodeOpen(@RequestBody ScanCodeOpenReq scanCodeOpenReq)
        throws RemotingSendRequestException, RemotingConnectException, RemotingTimeoutException, InterruptedException {
        RemotingCommand command = new RemotingCommand();
        command.setCommand((byte)5);
        byte[] body = {(byte)0x01};
        command.setBody(body);
        RemotingCommand remotingCommand = nettyTestServer.invokeSync(scanCodeOpenReq.getDeviceNo(), command);
        log.info("接受到数据：" + NetUtil.byte2HexStrSpace(remotingCommand.getBody()));
    }

    @PostMapping("/scanCodeOpenAsync")
    public void scanCodeOpenAsync(@RequestBody ScanCodeOpenReq scanCodeOpenReq) {
        RemotingCommand command = new RemotingCommand();
        command.setCommand((byte)5);
        byte[] body = {(byte)0x01};
        command.setBody(body);
        nettyTestServer.invokeAsyncFuture(scanCodeOpenReq.getDeviceNo(), command).thenAccept(response -> {
            log.info("接受到数据：" + NetUtil.byte2HexStrSpace(response.getBody()));
        });
    }
}
